package com.sinsz.wxpn;

import com.sinsz.common.exception.ApiException;
import com.sinsz.wxpn.support.Constant;
import org.springframework.context.ApplicationContext;

/**
 * 获取上下文
 * @author chenjianbo
 */
final class SpringContext {

    private static ApplicationContext applicationContext = null;

    private SpringContext() {
    }

    static void init(ApplicationContext context) {
        applicationContext = context;
        checkApplicationContext();
    }

    private static ApplicationContext getApplicationContext() {
        checkApplicationContext();
        return applicationContext;
    }

    /**
     * 检查是否已经注入上下文
     */
    private static void checkApplicationContext() {
        if (applicationContext == null) {
            throw new ApiException(Constant.DEFAULT_ERRORCODE, "上下文未配置");
        }
    }

    /**
     * 通过class获取Bean
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        checkApplicationContext();
        return getApplicationContext().getBean(clazz);
    }

    /**
     * 通过name获取 Bean
     *
     * @param name
     * @return
     */
    public static Object getBean(String name) {
        checkApplicationContext();
        return getApplicationContext().getBean(name);
    }

    /**
     * 通过name,以及Clazz返回指定的Bean
     *
     * @param name
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        checkApplicationContext();
        return getApplicationContext().getBean(name, clazz);
    }
}
